package com.ccteam.fluidmusic.ui.music

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.ConcatAdapter
import com.ccteam.fluidmusic.NavMoreMusicDirections
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentNewMusicBinding
import com.ccteam.fluidmusic.ui.artist.ArtistDetailMusicPagerFragment
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.view.adapters.GlobalDefaultMusicItemAdapter
import com.ccteam.fluidmusic.view.adapters.paging.CustomLoadStateAdapter
import com.ccteam.fluidmusic.view.adapters.toolbar.ToolbarTitleAdapter
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.MoreInfoData
import com.ccteam.fluidmusic.widget.AnimToolbarScrollListener
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.shared.result.music.DefaultMusicItem
import com.ccteam.shared.result.title.ToolbarTitleItem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class NewMusicFragment : Fragment() {

    private var _binding: FragmentNewMusicBinding? = null
    private val binding get() = _binding!!

    private val newMusicViewModel by viewModels<NewMusicViewModel>()
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    @Inject lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    /**
     * 是否是第一次加载
     * 如果不是第一次启动，则需要在分页数据更新时再次刷新一下数据，否则正在播放内容不会正确进行同步
     */
    private var isFirstLoad: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentNewMusicBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val titleAdapter = ToolbarTitleAdapter()
        titleAdapter.submitList(mutableListOf(ToolbarTitleItem(getString(R.string.online_music_new_music))))

        binding.toolbarAlbumList.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        val dataAdapter = ArtistDetailMusicPagerFragment.ArtistMusicListAdapter(callback)

        // 设置回弹效果
        lightBounceEdgeEffectFactory.applyBounceView(binding.rvNewMusic,this)
        binding.rvNewMusic.edgeEffectFactory = lightBounceEdgeEffectFactory
        binding.rvNewMusic.addOnScrollListener(AnimToolbarScrollListener(binding.toolbarTitle))

        val concatAdapter = ConcatAdapter(titleAdapter,dataAdapter.withLoadStateFooter(
            CustomLoadStateAdapter(dataAdapter,true){
                dataAdapter.retry()
            }
        ))
        binding.rvNewMusic.adapter = concatAdapter

        newMusicViewModel.newMusicListLiveData.observe(viewLifecycleOwner, {
            // 如果不是第一次加载，而是回退到此界面，则手动刷新一下数据
            if(!isFirstLoad){
                viewLifecycleOwner.lifecycleScope.launch {
                    newMusicViewModel.refreshNowPlaying()
                    isFirstLoad = true
                }
            }
            dataAdapter.submitData(viewLifecycleOwner.lifecycle,it)
        })

        viewLifecycleOwner.lifecycleScope.launch {
            dataAdapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && dataAdapter.itemCount < 1)
            }
        }

        binding.statusView.setRetryClickListener {
            dataAdapter.refresh()
        }
    }

    private val callback = object: GlobalDefaultMusicItemAdapter.DefaultMusicItemClickCallback{

        override fun musicItemClicked(item: DefaultMusicItem) {
            mainActivityViewModel.playMediaId(item.mediaId,newMusicViewModel.parentId,false)
        }

        override fun moreClicked(item: DefaultMusicItem) {
            findNavController().navigate(
                NavMoreMusicDirections.actionGlobalMusicMoreBottomSheetFragment(
                    MoreInfoData(newMusicViewModel.parentId,item.mediaId,item.title,
                        item.subtitle,false,item.albumId,item.artistInfo,item.albumArtUri)
                ))
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        isFirstLoad = false
        binding.rvNewMusic.clearOnScrollListeners()

        _binding = null
    }
}